package cn.autumnorange.app.common.consumer.rpc.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * Created on 2018/4/28.
 *
 * @author zlf
 * @since 1.0
 */
// @ComponentScan(basePackages = "cn.autumnorange.user.commons.entity.*")
@RestController
@Slf4j
public class RedisLockApplication {
  @Autowired private RedisLockRegistry redisLockRegistry;

  @GetMapping("redisLockRegistry/{redisLockRegistryName}")
  public String test(@PathVariable String redisLockRegistryName) throws InterruptedException {
    Lock lock = null;
    try {
      lock = redisLockRegistry.obtain("lock");
      //      在3s内尝试加锁加锁成功返回true
      boolean lockResult = lock.tryLock(3, TimeUnit.SECONDS);
      log.info("{} 加锁是否成功 : {}", redisLockRegistryName, lockResult);
    } catch (Exception e) {
      log.error(e.getMessage());
    } finally {
      if (lock != null) lock.unlock();
    }
    //    TimeUnit.SECONDS.sleep(5);
    return redisLockRegistryName;
  }
}
